var currentShiftID = "";
var localMode = false;
var tab5_oldShiftSpan;

/**
 * BO Tab4 ViewModel
 */
var headerVM = function() {
	var self = this;
	console.log("sectionTitle logged:: ", sectionTitle);
	self.sectionTitle = ko.observable(sectionTitle);
	console.log("sectionTitle logged:: ", sectionTitle);
};
var rootSelf;
var myMainTab5ViewModel = function() {
	var self = this;
	rootSelf = this;
	self.ClassRoomVOarr = ko.observableArray([]);
	self.RoomInfraVOarr = ko.observableArray([]);
	self.ShiftVOarr = ko.observableArray([]);

	self.TeachersListVOarr = ko.observableArray([]);
	self.ClassTeacherArray = ko.observableArray([]);

	// BO infra dialog
	self.myCurrentBuilding = ko.observable(null);
	self.myCurrentFloor = ko.observable(null);
	self.myCurrentRoom = ko.observable(null);
	self.selectedInfraID = ko.observable();

	self.myInfraTitle = ko.observable();
	self.isTeacherEditMode = ko.observable(isTeacherEditMode);

	self.onComboChange = function(item, event) {
		if (self.myCurrentFloor()) {

			ko.utils.arrayForEach(self.myCurrentFloor().childs(), function(item) {
				item.selectedRoomInfraId(self.itemForEditingClassRoomVO().infraId());
				//console.log("item.selectedRoomInfraId ", item.selectedRoomInfraId());
				//console.log("self.itemForEditingClassRoomVO().infraId() ", self.itemForEditingClassRoomVO().infraId());
				//console.log("item.infraId() ", item.infraId());
			});
		}
	};
	/**
	 * Update the array for available class teachers.
	 */
	self.availableClassTeachers = ko.computed(function() {
		var resultReturn = [];
		var allTeachersIDArr = new Array();
		for (var j = 0; j < rootSelf.TeachersListVOarr().length; j++) {

			var myTeacherItem = rootSelf.TeachersListVOarr()[j];

			if (myTeacherItem.userId.disableItem()) {

			} else {
				resultReturn.push(myTeacherItem);
				//console.log(j + " myTeacherItem.fullName() :: ", myTeacherItem.fullName());
			};
		}
		return resultReturn;

	});
	self.isValidItemToSave = ko.computed({
		read : function() {
			var resultReturn = true;
			//console.log("*********************** this.ClassRoomVOarr.length :: ", this.ClassRoomVOarr().length);
			if (this.itemForEditingClassRoomVO()) {
				ko.utils.arrayForEach(this.itemForEditingClassRoomVO().subjectTeachers(), function(item) {
					if (!item.subjectId.teacherAssigned()) {
						resultReturn = false;
					}
				});

				ko.utils.arrayForEach(this.itemForEditingClassRoomVO().coCurrTeachers(), function(item) {
					if (!item.subjectId.teacherAssigned()) {
						resultReturn = false;
					}
				});

			} else {

			}

			return resultReturn;
		},
		deferEvaluation : true //don’t evaluate until someone requests the value
	}, this);

	self.onRoomClick = function(item) {
		self.selectedInfraID(this.infraId());
		if (item) {
			self.myCurrentRoom(item);
		}

		//console.log("myMainTab5ViewModel onRoomClick .........this.infraId. :: ", this.infraId);
		self.acceptItemClassRoom(item);
	};

	self.onOKClick = function(data, event) {
		//console.log("onSelectMouseOut ......rrrrrrrrrr....")
		//console.log("onOKClick .........data. :: ", data)
		//console.log("onOKClick .........this. :: ", this);
		self.closeInfra();
	};

	if (localMode) {
		self.getSecClassTeachersUrl = "../json/tab5/getSchoolTeachers.json";
		self.getSchoolTeachersUrl = "../json/tab5/getSchoolTeachers.json";
		console.log(self.getSchoolTeachersUrl + " ok if localMode");
		self.getSchoolBuildingRoomsUrl = "../json/tab5/getSchoolBuildingRooms.json";
		self.getSecShiftsBySectionUrl = "../json/tab5/getSecShiftsBySection.json";
		self.getSecShiftClassTeachersUrl = "../json/tab5/getSecShiftClassTeachers.json";
	} else {
		//self.getSchoolTeachersUrl = "../json/tab5/getSchoolTeachers.json"
		//for getting all class teachers
		self.getSecClassTeachersUrl = baseOperationUrl + "getSecClassTeachers&aypId=" + aypId;
		self.getSchoolTeachersUrl = baseOperationUrl + "getSchoolTeachers&sectionId=" + sectionId;
		self.getSchoolBuildingRoomsUrl = baseOperationUrl + "getSchoolBuildingRooms&sectionId=" + sectionId;
		//self.getSchoolBuildingRoomsUrl = "../json/tab5/getSchoolBuildingRooms.json";
		self.getSecShiftsBySectionUrl = baseOperationUrl + "getSecShiftsBySection&sectionId=" + sectionId;
		self.getSecShiftClassTeachersUrl = baseOperationUrl + "getSecShiftClassTeachers&sectionId=" + sectionId;
		console.log(self.getSchoolBuildingRoomsUrl + " getSchoolBuildingRoomsUrl ok else localMode ");
	}
	//self.url = "../json/tab4/tab4_Scholastic_Server_Save.json";

	// all Grades list

	this.itemToAdd = ko.observable();
	this.itemParentToAdd = ko.observable();

	//hold the currently selected item
	this.selectedItem = ko.observable();

	//make edits to a copy

	this.itemForEditing = ko.observable();
	this.itemForEditingClassRoomVO = ko.observable();

	this.selectItem = this.selectItem.bind(this);
	this.selectItemAssign = this.selectItemAssign.bind(this);
	this.selectItemClassRoom = this.selectItemClassRoom.bind(this);

	this.selectedItemClassRoomVO = ko.observable();

	this.selectedInfraID = this.selectedInfraID.bind(this);
	//this.acceptItem = this.acceptItem.bind(this);
	this.acceptItemClassRoomTeacher = this.acceptItemClassRoomTeacher.bind(this);

	this.revertShiftItem = this.revertShiftItem.bind(this);
	this.revertItem = this.revertItem.bind(this);

	/** BO viewTeacherUtilization */

	this.teacherStaffViewModel = ko.observable();
	this.teacherStaffViewModel(new TeacherStaffViewModel());

	self.viewTeacherUtilization = function() {
		//this.isErrorDialogOpen(true);
		console.log("viewTeacherUtilization :: ");
		//dialog-viewTeacherUtilization
		self.openTeacherUtilizationDialog();
		self.errorTitle("Teacher Utilization: " + aypTitle);
	};
	self.isTeacherUtilizationDialogOpen = ko.observable(false);
	self.openTeacherUtilizationDialog = function() {
		this.isTeacherUtilizationDialogOpen(true);
		console.log("2014-01-29 this.teacherStaffViewModel() :: ",this.teacherStaffViewModel()); 
		this.teacherStaffViewModel().getData();
	};
	self.closeTeacherUtilizationDialog = function() {
		console.log("closeTeacherUtilizationDialog this :: ", this);
		console.log("closeTeacherUtilizationDialog this.isTeacherUtilizationDialogOpen() :: ", this.isTeacherUtilizationDialogOpen());
		this.isTeacherUtilizationDialogOpen(false);
	};
	/** EO viewTeacherUtilization */
	/////////////////////////////////

	self.isErrorDialogOpen = ko.observable(false);
	self.openErrorDialog = function() {
		this.isErrorDialogOpen(true);
	};
	self.closeErrorDialog = function() {
		this.isErrorDialogOpen(false);
	};
	/////
	self.isOpen = ko.observable(false);
	self.open = function() {
		this.isOpen(true);
	};
	self.close = function() {
		this.isOpen(false);
	};
	/////////////////////////////////
	self.isInfraOpen = ko.observable(false);
	self.openInfra = function() {
		this.isInfraOpen(true);
	};
	self.closeInfra = function() {
		this.isInfraOpen(false);
	};
	//
	self.isSaveDialogOpen = ko.observable(false);
	self.openSaveDialog = function() {
		this.isSaveDialogOpen(true);
	};
	self.closeSaveDialog = function() {
		this.isSaveDialogOpen(false);
		//this.close();
	};

	self.errorTitle = ko.observable("Some Error Title!!!");
	self.errorDesc = ko.observable("Some Error !!!");

	self.mytitle = ko.observable();
	self.myShiftTitle = ko.observable();
	self.lastSavedJson = ko.observable("");

	self.onAssignItemSaved = function(isForced) {
		/**
		 * BO Validation
		 */
		var errorExists = false;
		var editedItem = self.itemForEditingClassRoomVO();
		if (editedItem.errors().length != 0) {
			//verifying the errors attribute using the count of errors
			editedItem.errors.showAllMessages(true);
			//displaying the corresponding error messages
			errorExists = true;
			//set error flag to stop further processing
		}
		console.log("ccccccccccccc itemerrorExists:: ", errorExists);
		if (errorExists) {
			rootSelf.errorTitle("Fill All Fields");
			rootSelf.errorDesc("Please Fill All required Fields");

			this.openErrorDialog();
			return;
			//returning the control providing user a chance to correct the issues
		}
		if (editedItem.infraTitle() == "") {
			rootSelf.errorTitle("Select Room Number");
			rootSelf.errorDesc("Please Select a Room");

			this.openErrorDialog();
			return;
			//returning the control providing user a chance to correct the issues
		}

		if (!editedItem.teacherId.CTisST()) {
			console.log("editedItem.teacherId.CTisST() :: ", editedItem.teacherId.CTisST());

			rootSelf.errorTitle("Class Teacher");
			rootSelf.errorDesc("Class Teacher should takeup a Subject");

			this.openErrorDialog();
			return;
		}

		/**
		 * EO Validation
		 */
		var mapping = {
			'ignore' : ["errors"]
		};

		var edited = ko.toJS(this.itemForEditingClassRoomVO());

		//TODO : Edit Now
		/**
		 * Check if parent subject has teacher assigned
		 * then delete the SubSubjects
		 */
		ko.utils.arrayForEach(this.itemForEditingClassRoomVO().subjectTeachers(), function(myItem) {
			if (myItem.teacherId()) {
				myItem.subSubjects([]);
			}
		});

		//var saveDataStr = ko.mapping.toJSON(self.ClassRoomVOarr, mapping);
		var saveDataStr = ko.mapping.toJSON(self.itemForEditingClassRoomVO, mapping);
		//saveDataStr = "[" + saveDataStr + "]";

		console.log("-------- saveDataStr \n", saveDataStr);
		//console.log("ClassRoomVOarr edited :: ", self.ClassRoomVOarr());
		//console.log("self.isValidItemToSave : ", self.isValidItemToSave());

		if (isForced) {
			//console.log("saveDataStr \n", saveDataStr);
			saveTab5DataToServer(saveDataStr);
			loadSecClassTeachers();
			//console.log("data Saved ================================ isForced ");
		} else if (self.isValidItemToSave()) {
			//console.log("saveDataStr \n", saveDataStr);
			saveTab5DataToServer(saveDataStr);
			loadSecClassTeachers();
			/**
			 * Close the Dialog and make the editing Item as null.
			 */
			this.close();
			//clear selected item
			this.selectedItemClassRoomVO(null);
			this.itemForEditingClassRoomVO(null);

		} else if (!self.isValidItemToSave()) {
			self.openSaveDialog();
		} else {
			console.log("last else error:: ");
		}

		self.lastSavedJson(JSON.stringify(ko.toJS(self.ClassRoomVOarr), null, 2));
	};

	//Load list of Subjects also;

	//self.init()
	self.init = function() {
		loadBuildingInfraList();
	};

	//shift IDs
	self.clickedShiftID = ko.observable("");

	//button IDs
	self.clickedButton = ko.observable("");
	self.currentButton = ko.observable("");

	self.clickedBtnID = ko.observable("");

	/**
	 * Called from Html
	 */
	self.shiftClick = function(item) {
		console.log("item.shiftId() :: ", item.shiftId());
		console.log("item.shiftTitle() :: ", item.shiftTitle());
		self.clickedShiftID(item.shiftId());

		self.myShiftTitle(item.shiftTitle());

		if (item.shiftId() != currentShiftID) {
			self.openShiftChange();
		}
	};

	/**
	 * Called on Confirm No
	 */
	self.revertShiftChange = function() {
		//Change the clickedShiftID button to Current one
		self.clickedShiftID(currentShiftID);
		//click the currentButton to change the Selection
		self.currentButton().click();
		//Change the Clicked button to Current one
		self.clickedButton(self.currentButton());
		self.closeShiftChange();
	};
	/**
	 * Called on Confirm Yes
	 */
	self.changeShiftRoot = function(item) {
		currentShiftID = self.clickedShiftID();
		//Change the Clicked button to Current one
		self.currentButton(self.clickedButton());
		self.closeShiftChange();
		//load the rooms here.
		self.loadRoomsList();
		//console.log("rooooot changeShift :: ");

	};
	/////////////////////////////////
	self.isShiftChangeOpen = ko.observable(false);
	self.openShiftChange = function() {
		this.isShiftChangeOpen(true);
	};
	self.closeShiftChange = function() {
		this.isShiftChangeOpen(false);
	};

	function loadShiftsList() {
		var jqxhr = $.getJSON(self.getSecShiftsBySectionUrl, {
			returnformat : 'json'
		}, function(allData) {
			console.log("loadShiftsList allData :: ", allData);
			var mappedData = jQuery.map(allData, function(item) {
				console.log("currentShiftID :: ", currentShiftID);
				if (!currentShiftID) {
					currentShiftID = item.shiftId;

				}
				return new ShiftVO(item);
			});
			//Done: Make it Global in the Model and access like Combo functionality.
			self.ShiftVOarr(mappedData);
		});
		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
			//console.log("second success", allData[0]);
		});
		jqxhr.fail(function() {
			console.log("error loadShiftsList Url :: ", self.getSecShiftsBySectionUrl);
		});
		jqxhr.always(function() {
			//console.log("complete");
		});
		jqxhr.complete(function() {
			//console.log("complete loadShiftsList Url :: ", self.getSecShiftsBySectionUrl);
			//console.log("second complete");

			//the Shift 1

			//activate the class after the ui is populated by data
			$('#rad_buttons span').click(function(event, opt) {
				$('.active').removeClass('active');
				var $btn = $(this).addClass('active');
				var idx = $btn.index();
				console.log("event.currentTarget.nodeName :: ", event.currentTarget.nodeName);
				//Load the roomlist now.
				//loadRoomsList();

				/**
				 * Check if it is Span then clicked from Button
				 * Else it is From Submit or Cancel
				 */
				if (event.currentTarget.nodeName == "SPAN") {
					self.clickedButton($btn);

				}

				self.clickedBtnID(idx);

			});

			/**
			 * Call initially the Shift 1
			 */
			var btn;
			if (self.clickedBtnID()) {
				btn = $('#rad_buttons span')[self.clickedBtnID()];
				self.clickedBtnID(self.clickedBtnID());
			} else {
				btn = $('#rad_buttons span')[0];
				self.clickedBtnID(0);
			}
			if (btn) {
				btn.click();
				self.currentButton(btn);
				self.clickedButton(btn);
			};

			//
			self.loadRoomsList();

			showLoader(false);
		});
		/** ----------------------------------------- End Event Listeners */
	}


	self.loadRoomsList = function() {
		console.log("=========== self.getSecShiftClassTeachersUrl :: ", self.getSecShiftClassTeachersUrl);
		var fullUrl = self.getSecShiftClassTeachersUrl + "&shiftId=" + currentShiftID;
		console.log("=========== fullUrl :: ", fullUrl);
		var jqxhr = $.getJSON(fullUrl, {
			//&shiftId=shift-8e89526b-4ac2-4eca-8560-c278e0921faf
			returnformat : 'json'
		}, function(allData) {
			console.log("loadRoomsList allData :: ", allData);
			var mappedData = jQuery.map(allData, function(item) {
				return new ClassRoomVO(item);
			});
			//Done: Make it Global in the Model and access like Combo functionality.
			self.ClassRoomVOarr(mappedData);
		});
		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
			console.log("second success", allData);
		});
		jqxhr.fail(function() {
			console.log("........ error getSecShiftClassTeachersUrl Url :: ", self.getSecShiftClassTeachersUrl);
		});
		jqxhr.always(function() {
			//console.log("complete");
		});
		jqxhr.complete(function() {
			//console.log("second complete");
		});
		/** ----------------------------------------- End Event Listeners */
	};
	function loadBuildingInfraList() {
		showLoader(true, TYPE_LOADING);

		var jqxhr = $.getJSON(self.getSchoolBuildingRoomsUrl, {
			returnformat : 'json'
		}, function(allData) {
			console.log("loadRoomsList allData :: ", allData);
			var mappedData = jQuery.map(allData, function(item) {
				return new RoomInfraVO(item);
			});
			//Done: Make it Global in the Model and access like Combo functionality.
			self.RoomInfraVOarr(mappedData);
		});
		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
			//console.log("second success", allData[0]);
		});
		jqxhr.fail(function() {
			console.log("........ error getSchoolBuildingRoomsUrl Url :: ", self.getSchoolBuildingRoomsUrl);
		});
		jqxhr.always(function() {
			//console.log("........ complete loadRoomsList Url :: ", self.getSchoolBuildingRoomsUrl);
			//console.log("complete");
		});
		jqxhr.complete(function() {
			//console.log("second complete");
			loadSecClassTeachers(true);
		});
		/** ----------------------------------------- End Event Listeners */
	}

	function loadTeachersList() {
		console.log("loadTeachersList getSchoolTeachersUrl :: ", self.getSchoolTeachersUrl);
		var jqxhr = $.getJSON(self.getSchoolTeachersUrl, {
			returnformat : 'json'
		}, function(allData) {
			console.log("loadTeachersList allData :: ", allData);
			var mappedData = jQuery.map(allData, function(item) {
				return new TeacherVO(item);
			});
			//Done: Make it Global in the Model and access like Combo functionality.
			self.TeachersListVOarr(mappedData);

		});
		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
			//console.log("second success", allData[0]);
		});
		jqxhr.fail(function() {
			console.log("error loadTeachersList Url :: ", self.getSchoolTeachersUrl);
		});
		jqxhr.always(function() {
			//console.log("complete");
		});
		jqxhr.complete(function() {
			//console.log("second complete");
			loadShiftsList();

		});
		/** ----------------------------------------- End Event Listeners */
	}

	/**
	 * Load all ClassTeachers for that Section
	 * Needed for Filteration and disable them for ClassTeacher Seletion
	 */
	function loadSecClassTeachers(isFirstTime) {
		var jqxhr = $.getJSON(self.getSecClassTeachersUrl, {
			returnformat : 'json'
		}, function(allData) {
			console.log("loadSecClassTeachers allData :: ", allData);
			var mappedData = jQuery.map(allData, function(item) {
				return new ClassTeacherVO(item);

			});
			//Done: Make it Global in the Model and access like Combo functionality.
			rootSelf.ClassTeacherArray(mappedData);
		});
		/** ----------------------------------------- Event Listeners */
		jqxhr.done(function(allData) {
			/* Working the Object Access */
			//console.log("second success", allData[0]);
		});
		jqxhr.fail(function() {
			console.log("error getSecClassTeachers Url :: ", self.getSecClassTeachersUrl);
		});
		jqxhr.always(function() {
			//console.log("complete loadSecClassTeachers");
		});
		jqxhr.complete(function() {
			console.log("second complete loadSecClassTeachers");
			if (isFirstTime) {
				loadTeachersList();
			} else {
				showLoader(false);
			}
		});
		/** ----------------------------------------- End Event Listeners */
	}

};

ko.utils.extend(myMainTab5ViewModel.prototype, {
	//Prasanna

	//select an item and make a copy of it for editing

	selectItem : function(item) {

	},
	loadMyRooms : function(item) {
		console.log("loadMyRooms :: ");
		this.loadRoomsList();
	},
	selectItemClassRoom : function(item) {

		/**
		 * Reset the vars for infras
		 *
		 // BO infra dialog
		 self.myCurrentBuilding
		 self.myCurrentFloor
		 self.myCurrentRoom
		 self.selectedInfraID
		 *
		 */
		var mySelf = this;
		var resultReturn = false;
		ko.utils.arrayForEach(this.RoomInfraVOarr(), function(itemBuilding) {
			//
			ko.utils.arrayForEach(itemBuilding.childs(), function(itemFloor) {
				//
				ko.utils.arrayForEach(itemFloor.childs(), function(itemRoom) {
					if (item) {
						if (item.infraId() == itemRoom.infraId()) {
							mySelf.myCurrentBuilding(itemBuilding);
							mySelf.myCurrentFloor(itemFloor);
							mySelf.myCurrentRoom(itemRoom);
							itemRoom.selectedRoomInfraId(item.infraId());
							resultReturn = true;
						} else {
							/**
							 * Deselect the other ones.
							 */
							itemRoom.selectedRoomInfraId(null);
						}
					};

				});
			});

		});

		myTab5Mode = "selectClassRoom";
		//console.log("selectItemClassRoom ...xxxxxxxxxxxxxxxxxxxxxxxx......this. :: ", this)
		if (this.itemForEditingClassRoomVO()) {

		} else {
			this.selectedItemClassRoomVO(item);
			this.itemForEditingClassRoomVO(new ClassRoomVO(ko.toJS(item), myTab5Mode));
		}

		this.openInfra();
	},

	selectItemAssign : function(item) {

		this.open();
		myTab5Mode = "defineSubject";
		//set the item to be added for term
		//this.itemToAdd = new ClassRoomVO(ko.toJS(item), myTab5Mode)
		//this.updateClassTeacherArray();
		this.selectedItemClassRoomVO(item);
		this.itemForEditingClassRoomVO(new ClassRoomVO(ko.toJS(item), myTab5Mode));

		//this.mytitle("Assign");
		this.myShiftTitle("Morning");
		this.mytitle("Assign Teachers for " + item.gradeTitle() + " " + item.divisionTitle());
		console.log("this :: ", this)

		this.itemForEditingClassRoomVO().errors.showAllMessages(false);

		/**
		 * Show Room Selection Dialog if Room not Selected.
		 */

		if (this.itemForEditingClassRoomVO().infraTitle() == "") {
			//rootSelf.errorTitle("Select Room Number");
			//rootSelf.errorDesc("Please Select a Room");
			//this.openErrorDialog();

			rootSelf.selectItemClassRoom();
		}

	},

	acceptItemClassRoom : function(infraVOitem) {

		myTab5Mode = "saveClassroom";
		this.closeInfra();

		this.itemForEditingClassRoomVO().infraId(infraVOitem.infraId());
		this.itemForEditingClassRoomVO().infraTitle(this.itemForEditingClassRoomVO().teacherId.rootRoomDesc());

		//var selected = this.selectedItemClassRoomVO();
		//var edited = ko.toJS(this.itemForEditingClassRoomVO());

		//clean copy of edited
		//apply updates from the edited item to the selected item
		//selected.update(edited, myTab5Mode);

		//selected.infraTitle(this.rootRoomDesc());

		//console.log("selected.infraTitle ==============:: ", selected.infraTitle())

		//clear selected item

		//commented by Prasanna newone
		//this.selectedItemClassRoomVO(null);
		//this.itemForEditingClassRoomVO(null);
	},
	acceptItemClassRoomTeacher : function(item) {

		myTab5Mode = "saveSubject";

		var selected = this.selectedItemClassRoomVO();
		var edited = ko.toJS(this.itemForEditingClassRoomVO());

		console.log("acceptItemClassRoomTeacher edited :: ", edited);

		//clean copy of edited
		//apply updates from the edited item to the selected item
		selected.update(edited, myTab5Mode);

		if (!this.isValidItemToSave()) {
			this.openSaveDialog();
		} else {
			this.onAssignItemSaved();
		}

	},
	acceptItemForce : function(item) {

		this.onAssignItemSaved(true);
		this.closeSaveDialog();
		/**
		 * Close the Dialog and make the editing Item as null.
		 */
		this.close();
		//clear selected item
		this.selectedItemClassRoomVO(null);
		this.itemForEditingClassRoomVO(null);
	},

	RevertRoomSelection : function() {
		//Prasanna
		this.closeInfra();

		//commented by Prasanna newone
		this.myCurrentFloor(null);
	},
	revertShiftItem : function() {
		//Prasanna
		//this.close();
	},
	//just throw away the edited item and clear the selected observables
	revertItem : function() {
		//Prasanna
		this.close();
		this.selectedItem(null);
		this.itemForEditing(null);

		this.selectedItemClassRoomVO(null);
		this.itemForEditingClassRoomVO(null);
	}
});
// ====================================================================== EO new Model implementation //////////////
/**
 * EO Tab4 ViewModel
 */

// ====================================================================== BO new Model implementation //////////////
var myTab5Mode = "addAssessment";

// new ones edited from Example
var SubjectTeacherVO = function(data) {
	var self = this;
	this.teacherId = ko.observable("");
	this.subjectId = ko.observable("");
	this.subjectTitle = ko.observable("");
	this.subSubjects = ko.observableArray([]);

	this.subSubjects.comboEnabled = ko.computed(function() {

		var allEmpty = true;
		for (var i = 0; i < self.subSubjects().length; i++) {
			if (!self.teacherId()) {
				//Reassign the value as it gets striped from the VO
				self.teacherId("");
			}
			var subSubjectVO = self.subSubjects()[i];
			if (subSubjectVO.teacherId()) {
				allEmpty = false;
				break;
			} else {
				//Reassign the value as it gets striped from the VO
				subSubjectVO.teacherId("");
			}
		};
		return allEmpty;
	}, this);

	this.subjectId.teacherAssigned = ko.computed(function() {

		var returnVal = false;

		if (self.subSubjects().length > 0) {
			/**
			 * Remove parent teacher id if assigned.
			 */
			//console.log("xxxxxxxxxxxxxxxxx remove self.teacherId() :: ", self.teacherId());
			self.teacherId("");
		}

		if (self.teacherId()) {
			/**
			 * If Subject has assigned teacher
			 */
			returnVal = true;
			return returnVal;
		} else {
			//Reassign the value as it gets striped from the VO
			self.teacherId("");
			//console.log("======self.teacherId() :: ", self.teacherId());
			//console.log("self.subSubjects().length :: ", self.subSubjects().length);
			returnVal = true;
			for (var i = 0; i < self.subSubjects().length; i++) {
				var subSubjectVO = self.subSubjects()[i];
				if (!subSubjectVO.teacherId()) {
					/**
					 * If any of the SubSubject has not assigned teacher
					 */
					returnVal = false;
					break;
				}
			};

			if (self.subSubjects().length == 0) {
				returnVal = false;
			}
		}
		//console.log("returnVal :: ", returnVal);
		return returnVal;
	}, this);
	this.onSubjectTeacherChange = function() {
		return;

	};
	this.onSubSubjectTeacherChange = function(item, event) {
		return;
	};

	this.cache = function() {
	};
	this.update(data);
};

ko.utils.extend(SubjectTeacherVO.prototype, {
	update : function(data) {
		this.teacherId(data.teacherId || "");
		this.subjectId(data.subjectId || "");
		this.subjectTitle(data.subjectTitle || "");

		if (!this.teacherId()) {
			//Reassign the value as it gets striped from the VO
			this.teacherId("");
		}
		var tempMappedData;
		//sub Subjects
		if (data.subSubjects) {

			tempMappedData = jQuery.map(data.subSubjects, function(item) {
				return new SubjectTeacherVO(item);
			});
			this.subSubjects(tempMappedData);

		} else {
			this.subSubjects([]);
		}

		//save off the latest data for later use
		this.cache.latestData = data;
		//	console.log(this.subjectTitle() + " :: ================= this.teacherId :: ", this.teacherId());
	},
	revert : function() {
		this.update(this.cache.latestData);
	}
});

var ClassTeacherVO = function(data) {
	var self = this;
	this.teacherId = ko.observable("");
	this.title = ko.observable("");
	this.firstName = ko.observable("");
	this.middleName = ko.observable("");
	this.lastName = ko.observable("");

	this.cache = function() {
	};
	this.update(data);
};

ko.utils.extend(ClassTeacherVO.prototype, {
	update : function(data) {
		this.teacherId(data.teacherId || "");
		this.title(data.title || "");
		//console.log("ClassTeacherVO data.title :: ",data.title);
		this.firstName(data.firstName || "");
		this.middleName(data.middleName || "");
		this.lastName(data.lastName || "");
		//save off the latest data for later use
		this.cache.latestData = data;
	},
	revert : function() {
		this.update(this.cache.latestData);
	}
});

var TeacherVO = function(data) {
	var self = this;
	this.userId = ko.observable("");
	this.title = ko.observable("");
	this.firstName = ko.observable("");
	this.middleName = ko.observable("");
	this.lastName = ko.observable("");

	//Create var for setting the disable to the item;

	this.userId.disableItem = ko.computed(function() {
		var isClassTeacher = false;
		for (var i = 0; i < rootSelf.ClassTeacherArray().length; i++) {
			if (rootSelf.ClassTeacherArray()[i].teacherId() == self.userId()) {
				//console.log("teacher userId  :: ", self.userId() + " ClassTeacher userId() :: ", rootSelf.ClassTeacherArray()[i].teacherId());
				//Got matched with the class teacher ID

				isClassTeacher = true;
				break;
			}
		};

		// DONE: Check if the Class's Class Techer then do not disable.
		if (rootSelf.selectedItemClassRoomVO()) {
			var currentClassTeacherID = rootSelf.selectedItemClassRoomVO().teacherId();
			//console.log("currentClassTeacherID :: ", currentClassTeacherID);
			//console.log("this.userId() :: ", this.userId());
			if (currentClassTeacherID == this.userId()) {
				isClassTeacher = false;
			}
		}

		return isClassTeacher;

	}, this);

	this.fullName = ko.computed(function() {
		return this.title() + " " + this.firstName() + " " + this.lastName();
	}, this);

	this.cache = function() {
	};
	this.update(data);
};
//can pass fresh data to this function at anytime to apply updates or revert to a prior version
ko.utils.extend(TeacherVO.prototype, {
	update : function(data) {
		this.userId(data.userId || "");
		this.title(data.title || "");
		//console.log("TeacherVO data.title :: ",data.title);
		this.firstName(data.firstName || "");
		this.middleName(data.middleName || "");
		this.lastName(data.lastName || "");
		//save off the latest data for later use
		this.cache.latestData = data;
	},
	revert : function() {
		this.update(this.cache.latestData);
	}
});

// parameter to pass "savedata"

function saveTab5DataToServer(saveDataStr) {

	var urlSaveTab5Data = baseOperationUrl + "saveSecShiftClassTeachers";
	console.log("urlSaveTab5Data :: " + urlSaveTab5Data);
	showLoader(true, TYPE_SAVING);
	//tab5ClassRoomViewModel.loadSecClassTeachers()
	//return;
	var localData = {
		savedata : saveDataStr
	};
	$.ajax({
		url : urlSaveTab5Data,
		type : 'POST',
		data : localData,
		dataType : 'json',
		async : false,
		success : function(msg) {
			showLoader(false);
			console.log("saveTab5DataToServer Operation copmpleted", msg);
		},
		error : jsonIOError
	});
}

var ClassRoomVO = function(data, mode) {
	var self = this;
	this.classId = ko.observable();
	this.gradeTitle = ko.observable();
	this.divisionTitle = ko.observable();
	this.infraId = ko.observable();

	this.infraId.myCurrentBuilding = ko.observable();
	this.infraId.myCurrentFloor = ko.observable();
	this.infraId.myCurrentRoom = ko.observable();
	this.subjectTeachers = ko.observableArray([]);

	this.coCurrTeachers = ko.observableArray([]);
	this.teacherId = ko.observable('').extend({
		required : true
	});

	this.infraTitle = ko.observable();

	self.teacherId.rootRoomDesc = ko.computed({
		read : function() {
			var item = self;
			ko.utils.arrayForEach(rootSelf.RoomInfraVOarr(), function(itemBuilding) {
				//
				ko.utils.arrayForEach(itemBuilding.childs(), function(itemFloor) {
					//
					ko.utils.arrayForEach(itemFloor.childs(), function(itemRoom) {
						if (item.infraId() == itemRoom.infraId()) {
							self.infraId.myCurrentBuilding(itemBuilding);
							self.infraId.myCurrentFloor(itemFloor);
							self.infraId.myCurrentRoom(itemRoom);
							itemRoom.selectedRoomInfraId(item.infraId());
							resultReturn = true;
						} else {
							/**
							 * Deselect the other ones.
							 */
							itemRoom.selectedRoomInfraId(null);
						}
					});
				});

			});

			var result = "";
			if (self.infraId.myCurrentBuilding()) {

				if (self.infraId.myCurrentRoom()) {

					if (self.infraId.myCurrentFloor()) {
						result = self.infraId.myCurrentRoom().title() + " (Bldg:" + self.infraId.myCurrentBuilding().title() + ", Floor:" + self.infraId.myCurrentFloor().title() + ")";
						//console.log("result in:: ============================", result);
					}
				}
			}

			//console.log("result :: ============================", result);
			return result;
		}
	}, this);

	this.teacherId.classTeacherName = ko.computed({
		read : function() {
			var resultReturn = "";
			ko.utils.arrayForEach(rootSelf.TeachersListVOarr(), function(item) {
				//result += item.teacherId() + "\n";
				if (item.userId() == self.teacherId()) {
					console.log("item.title() :: ", item.title());
					console.log("item.firstName() :: ", item.firstName());
					resultReturn = item.title() + " " + item.firstName() + " " + item.lastName();
				}
			});

			//console.log("classTeacherName :: ", resultReturn);
			return resultReturn;
		},
		deferEvaluation : true //don’t evaluate until someone requests the value
	}, this);

	//this.allTeachers = ko.observable();
	//TODO: Reevaluate after Arijit idea for this.
	self.teacherId.allTeachersIdPresent = ko.computed({
		read : function() {
			//Teachers not Assigned -1
			var resultReturn = 1;
			console.log("this.subjectTeachers() :: ", this.subjectTeachers());

			for (var i = 0; i < this.subjectTeachers().length; i++) {
				var item = this.subjectTeachers()[i];
				//console.log("item.subjectId.teacherAssigned() :: ", item.subjectId.teacherAssigned());
				if (!item.subjectId.teacherAssigned()) {
					resultReturn = -1;
					break;
				}
			};

			//2013-10-17
			console.log("resultReturn subjectTeachers:: ", resultReturn);

			if (resultReturn) {
				for (var i = 0; i < this.coCurrTeachers().length; i++) {
					var item = this.coCurrTeachers()[i];
					//console.log("coCurrTeachers xxxxxxxxxxxxx item.subjectId.teacherAssigned() :: ", item.subjectId.teacherAssigned());
					if (!item.subjectId.teacherAssigned()) {
						resultReturn = -1;
						break;
					}
				};
			};
			if (this.coCurrTeachers().length == 0 && this.subjectTeachers().length == 0) {
				resultReturn = 0;
			};
			console.log("resultReturn coCurrTeachers:: ", resultReturn);

			//console.log("+++++++++++++++++++ gradeTitle  divisionTitle:: ", self.gradeTitle() + " : " + self.divisionTitle())
			//console.log("resultReturn :: ", resultReturn)
			return resultReturn;
		},
		deferEvaluation : true //don’t evaluate until someone requests the value
	}, this);

	/**
	 * Check if the ClassTeacher is a SubjectTeacher
	 */
	self.teacherId.CTisST = ko.computed({
		read : function() {
			var resultReturn = false;
			ko.utils.arrayForEach(self.subjectTeachers(), function(item) {
				//class teacher is found to be a Subject Teacher.
				if (item.teacherId() == self.teacherId()) {
					resultReturn = true;
				}

				/**
				 * Check in subSubjects also
				 */
				ko.utils.arrayForEach(item.subSubjects(), function(subItem) {
					//class teacher is found to be a Subject Teacher.
					if (subItem.teacherId() == self.teacherId()) {
						resultReturn = true;
					}
				});

			});
			return resultReturn;
		},
		deferEvaluation : true //don’t evaluate until someone requests the value
	}, this);

	self.teacherId.teacherCountDesc = ko.computed({
		read : function() {
			var resultReturn = "";
			var teacherCount = 0;
			ko.utils.arrayForEach(this.subjectTeachers(), function(item) {
				if (item.subjectId.teacherAssigned()) {
					teacherCount += 1;
				}
			});
			resultReturn = teacherCount + "/" + this.subjectTeachers().length;
			//console.log("resultReturn teacherCount:: ", resultReturn);
			return resultReturn;
		},
		deferEvaluation : true //don’t evaluate until someone requests the value
	}, this);

	self.teacherId.allTeachers = ko.computed({
		read : function() {
			var result = "";
			ko.utils.arrayForEach(this.subjectTeachers(), function(item) {
				result += item.teacherId() + "\n";
			});
			//console.log("result >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> :: ", result);
			return result;
		},
		deferEvaluation : true //don’t evaluate until someone requests the value
	}, this);

	/**
	 * Used for Combo Item Disable

	 self.setOptionDisable = function(option, item) {
	 //console.log("item :: ", item);
	 if (item) {
	 //console.log("item.disable :: ", item.userId.disableItem);
	 ko.applyBindingsToNode(option, {
	 disable : item.userId.disableItem()
	 }, item);
	 }
	 };*/
	self.cache = function() {
	};
	//populate our model with the initial data
	self.update(data, mode);

	self.errors = ko.validation.group(self, {
		deep : true
	});
};

ko.utils.extend(ClassRoomVO.prototype, {
	update : function(data, mode) {
		//console.log("data.startDate :: " , data.startDate)
		this.classId(data.classId || "");
		this.gradeTitle(data.gradeTitle || "");
		this.divisionTitle(data.divisionTitle || "");
		this.infraId(data.infraId || '');
		this.teacherId(data.teacherId || '');
		this.infraTitle(data.infraTitle || '');

		//console.log("data.teacherId ------------------------------ :: ", data.teacherId);
		var tempMappedData;
		if (mode == "saveSubjectxxx") {
			//also update the terms array as it is if it is in editmode
			this.subjectTeachers(data.subjectTeachers);
		} else {
			// No need of else.
			tempMappedData = jQuery.map(data.subjectTeachers, function(item) {
				return new SubjectTeacherVO(item);
			});
			this.subjectTeachers(tempMappedData);

			//coCurrTeachers
			tempMappedData = jQuery.map(data.coCurrTeachers, function(item) {
				return new SubjectTeacherVO(item);
			});
			this.coCurrTeachers(tempMappedData);

		}
		//console.log("this.subjectTeachers xxxxxxxxxx :: ", this.subjectTeachers)
		//save off the latest data for later use
		this.cache.latestData = data;
	},
	revert : function() {
		this.update(this.cache.latestData, "");
	}
});

var RoomInfraVO = function(data, mode) {
	var self = this;
	this.title = ko.observable();
	this.parentId = ko.observable();
	this.infraDesc = ko.observable();
	this.infraId = ko.observable();
	this.selectedRoomInfraId = ko.observable();
	this.infraType = ko.observable();

	self.infraId.isSelected = ko.computed(function() {
		var isSelected = false;
		if (self.infraId == self.selectedInfraId) {
			isSelected = true;
		} else {
			isSelected = false;
		}
		return isSelected;
	});

	this.childs = ko.observableArray([]);

	self.cache = function() {
	};
	//populate our model with the initial data
	self.update(data, mode);
};

ko.utils.extend(RoomInfraVO.prototype, {
	update : function(data, mode) {
		//console.log("data.startDate :: " , data.startDate)
		this.title(data.title || "");
		this.parentId(data.parentId || "");
		this.infraDesc(data.infraDesc || "");
		this.infraId(data.infraId || "");
		this.infraType(data.infraType || 0);

		if (data.childs) {

			// if in edit mode
			var mappedData = jQuery.map(data.childs, function(item) {
				//Done: Need to create and update the RoomInfraVO for making the nested obsevables.
				return new RoomInfraVO(item);
			});
			this.childs = ko.observableArray(mappedData);

		}
		//save off the latest data for later use
		this.cache.latestData = data;
	},

	revert : function() {
		this.update(this.cache.latestData, "");
	}
});
var ShiftVO = function(data) {
	var self = this;

	this.isChecked = ko.observable();
	this.shiftId = ko.observable();
	this.shiftTitle = ko.observable();

	this.cache = function() {
	};
	this.update(data);

};

ko.utils.extend(ShiftVO.prototype, {
	update : function(data) {
		this.isChecked(data.isChecked || false);
		this.shiftId(data.shiftId || "");
		this.shiftTitle(data.shiftTitle || "");
		//save off the latest data for later use
		this.cache.latestData = data;
	},
	revert : function() {
		this.update(this.cache.latestData);
	}
});
/**
 *A Compare Function
 */
function compareSimpleArray(a, b) {
	if (a < b)
		return -1;
	if (a > b)
		return 1;
	return 0;
}